package com.flushbonading.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.flushbonading.pojo.User;

import java.util.Date;


/**
 * @author zyx 2134208960@qq.com
 * @version 0.1.0
 * @date 2021-03-18 08:00
 * @since 0.1.0
 **/
public class TokenUtils {
    /**
     * 设置token失效时间
     */
    private static final long EXPIRE_TIME = 10 * 60 * 60 * 1000;

    /**
     * 设置签名  保密  复杂
     */
    private static final String SING = "QRSBJ#$S%D!";


    /**
     * 得到token
     *
     * @param user
     * @return
     */
    public static String getUserToken(final User user) {
        String token = "";

        //设置token过期时间
        final Date expiresDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        token = JWT.create()
                .withAudience(user.getUser_id())
                .withExpiresAt(expiresDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token的合法性
     *
     * @param token 令牌
     */
    public static DecodedJWT verify(final String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

}
